import socket

def tcp_base():
    # 创建一个TCP/IP socket
    global server_socket
    server_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 绑定到所有网络接口和一个端口
    server_address = ('', 10000)
    server_socket.bind(server_address)

    # 开始监听连接
    server_socket.listen(1)

    print(f'服务器正在监听10000端口...')

def send_data_to_server_c(host, port, message):
    # 创建一个TCP/IP socket
    client_socket = socket.socket(socket.AF_INET, socket.SOCK_STREAM)

    # 连接到服务器
    client_socket.connect((host, port))

    try:
        # 发送数据
        client_socket.sendall(message.encode('utf-8'))

        # 接收服务器的响应（如果有的话）
        response = client_socket.recv(1024).decode('utf-8')
        print(f"服务器响应: {response}")

    finally:
        # 关闭连接
        client_socket.close()

def tcp_received():
    while True:
        # 等待接受一个连接
        print('等待连接...')
        global connection
        connection, client_address = server_socket.accept()
        print(f'已连接: {client_address}')

        ipaddress = client_address[0]
        port = client_address[1]
        message = "deck left get_level"

        print(ipaddress, port, message)
        send_data_to_server(message)

        try:
            # 接收数据
            while True:
                data = connection.recv(1024)
                if data:
                    # 打印接收到的数据
                    print(f"从{client_address}接收到的数据: {data.decode('utf-8')}")
                else:
                    # 如果没有数据，说明客户端关闭了连接
                    break
        finally:
            # 关闭连接
            connection.close()

def send_data_to_server(message):
    try:
        send_data(connection, message)

        # 接收客户端可能的响应（可选）
        client_response = connection.recv(1024).decode('utf-8')
        print(f"客户端响应: {client_response}")

    finally:
        # 关闭客户端连接
        connection.close()

def send_data(server_socket, message):
    # 发送数据
    server_socket.sendall(message.encode('utf-8'))

if __name__ == "__main__":
    tcp_base()
    tcp_received()
